<script>
import mqtt from 'mqtt'
import { mqttExtraConnection } from '@/utils/constant'
import { generateRandStr, isJson, Utf8ArrayToStr } from '@/utils'
export default {
  props: {
    topic: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      // devices: this.$store.getters.devicesObj,
      // serialnos: this.$store.getters.devices.map(val => (val.rtu_serialno || val.serialno)),
      connection: mqttExtraConnection,
      subscription: {
        topic: 'D/0103.0007.2038000000/#',
        qos: 0
      },
      client: {
        connected: false
      },
      subscribeSuccess: false
    }
  },
  methods: {
    // 创建连接
    createConnection() {
      // 连接字符串, 通过协议指定使用的连接方式
      // ws 未加密 WebSocket 连接
      // wss 加密 WebSocket 连接
      // mqtt 未加密 TCP 连接
      // mqtts 加密 TCP 连接
      // wxs 微信小程序连接
      // alis 支付宝小程序连接
      const { host, port, endpoint, ...options } = this.connection
      options.clientId = 'mqttjs_3be2c321' + generateRandStr()
      const connectUrl = `ws://${host}:${port}${endpoint}`
      try {
        if (!this.client.connected) {
          this.client = mqtt.connect(connectUrl, options)
        }
      } catch (error) {
        console.log('mqtt.connect error', error)
      }
      this.client.on('connect', () => {
        console.log('Connection succeeded1!')
        this.client.connected = true
        this.doSubscribe()
      })
      this.client.on('error', error => {
        console.log('Connection failed', error)
        this.doUnSubscribe()
      })
      this.client.on('message', (topic, message) => {
        const state_raw = Utf8ArrayToStr(message)
        const state =
          typeof state_raw === 'string' && isJson(state_raw)
            ? JSON.parse(state_raw)
            : {}
        const { a, b, rtk, dir } = state
        const stateFormat = {
          a: `${(a && a.x && a.x.toFixed(4)) || 0},${(a && a.y && a.y.toFixed(4)) || 0}`,
          b: `${(b && b.x && b.x.toFixed(4)) || 0},${(b && b.y && b.y.toFixed(4)) || 0}`,
          rtk: `${(rtk && rtk.x && rtk.x.toFixed(8)) || 0},${(rtk && rtk.y && rtk.y.toFixed(8)) || 0}`,
          dir: `${dir && dir.toFixed(4) || 0}`
        }
        // console.log(stateFormat)
        this.$store.commit('device/SET_RTK', stateFormat)
      })
    },
    doSubscribe() {
      if (!this.subscribeSuccess) {
        const { qos } = this.subscription
        this.client.subscribe(this.topic, qos, (error, res) => {
          if (error) {
            console.log('Subscribe to topics error', error)
            return
          }
          this.subscribeSuccess = true
          console.log('Subscribe to topics res', res)
        })
      }
    },
    doUnSubscribe() {
      this.client.unsubscribe(this.topic, error => {
        if (error) {
          console.log('Unsubscribe error', error)
        }
      })
    },
    destroyConnection() {
      if (this.client.connected) {
        try {
          this.doUnSubscribe()
          this.subscribeSuccess = false
          this.client.end()
          this.client = {
            connected: false
          }
          console.log('Successfully disconnected!')
        } catch (error) {
          console.log('Disconnect failed', error.toString())
        }
      }
    }
  },
  // eslint-disable-next-line vue/require-render-return
  render(h, context) { }
}
</script>
